<?php


namespace app\socket\services;


use app\api\services\GatewayService;
use app\common\model\ClientLogModel;
use app\common\model\ClientModel;
use app\common\model\ClientSignModel;
use app\common\model\MessageLogModel;
use app\common\model\StaffModel;
use app\common\model\StaffTicketModel;
use app\common\model\UserListModel;
use GatewayWorker\Lib\Gateway;
use utils\Jwt;

class LoginService extends BaseService
{
    /**
     * 新用户登录  （废弃）
     * 需要判断是 客服 还是 客户
     * 如果是客服 则创建 客服房间
     * 如果是客户 则选择加入客服房间
     * @param $message_data
     * @param $client_id  当前客户端消息id
     */
    public static function Login2($resData,$connection){

        $ticket = $resData['ticket'];
        if(empty($ticket)){
            Gateway::sendToCurrentClient(['err'=>'登录服务器失败！']);
            return ;
        }
        //解析基本信息
        $_userInfo = Jwt::verifyToken($ticket);
//        echo "收到登录请求,userinfo={$_userInfo['nickname']}[{$_userInfo['uid']}] 级别：{{$_userInfo['role']}}\n";
        if($_userInfo['role']==1){
            $userInfo = StaffModel::getInfo($_userInfo['uid']);
            $userInfo['role'] = $_userInfo['role'];
            //将客服信息 和 connection句柄关联起来
            UserInfoService::addKefu($connection,$userInfo);

            // 登录成功  返回当前在线的用户列表
            UserInfoService::getUserList();
        }else{
            //获取客户的基本信息
            $userInfo = ClientModel::getInfo($_userInfo['id']);
            $userInfo['role'] = $_userInfo['role'];
            //获取用户最近的附加信息
            $userInfo['login_info'] = ClientLogModel::findAll(['uid'=>$userInfo['id']],'ip,ip_text,source,header,os,create_time','id desc','3');
//            $userInfo = ClientModel::handleUserInfo($userInfo);
            UserInfoService::addClient($connection,$userInfo);
        }

    }

    /**
     * 废弃
     * @param $resData
     * @param $connection
     */
    public static function Login($resData,$connection){
        $ticket = $resData['ticket'];
        if(empty($ticket)){
            Gateway::sendToCurrentClient(['err'=>'登录服务器失败！']);
            return ;
        }
        //解析基本信息
        $_userInfo = Jwt::verifyToken($ticket);
//        dump($_userInfo);

//        if(isset($_userInfo['to_id'])){
//            dump('登录请求====>'.$_userInfo['id'].$_userInfo['nickname'].'====>to_id'.$_userInfo['to_id']);
//
//        }else{
//            dump('登录请求====>'.$_userInfo['id'].$_userInfo['nickname']);
//        }
//        dump($_userInfo);
//        echo "收到登录请求,userinfo={$_userInfo['nickname']}[{$_userInfo['uid']}] 级别：{{$_userInfo['role']}}\n";
        if($_userInfo['role']==1){
            $userInfo = StaffModel::getInfo($_userInfo['uid']);
            $userInfo['uuid'] = $_userInfo['uuid'];
            $userInfo['role'] = $_userInfo['role'];

            dump("登录请求====>UUID：{$_userInfo['uuid']} 昵称：{$_userInfo['nickname']}");

            //将客服信息 和 connection句柄关联起来
            UserInfoService::addKefu($connection,$userInfo);

            // 登录成功  返回当前会话列表
            UserInfoService::getUserList();
        }else{

            //获取客户的基本信息
            $userInfo = ClientModel::getInfo($_userInfo['id']);
            $userInfo['role'] = $_userInfo['role'];
            //获取用户最近的附加信息
            $userInfo['login_info'] = ClientLogModel::findAll(['uid'=>$userInfo['id']],'ip,ip_text,source,header,os,create_time','id desc','3');
            $userInfo['to_id'] = $_userInfo['to_id'];
            $userInfo['uuid'] = $_userInfo['id'];
            dump("登录请求====>UUID：{$_userInfo['uuid']} 昵称：{$_userInfo['nickname']} 客服组ID：{$userInfo['depart_id']} 客服ID：{$userInfo['staff_id']}");

            UserInfoService::addClient($connection,$userInfo);
            // 登录成功  返回我的会话列表
            UserInfoService::getUserList();

            //通知大家 我上线了
            self::popUpOnline($userInfo);

        }

    }

    /**
     *  新版登录
     */
    public static function login3($resData,$client_id){
        // 用户的ticket
        $ticket = $resData['ticket'];

        //获取用户的id
        $uid = ClientSignModel::findValue(['ticket'=>$ticket],'uid');

        //获取登录的用户信息
        $userInfo = ClientModel::findOne(['id'=>$uid],'id,admin_id');

        LogService::save('用户登录',['ticket'=>$ticket,'uid'=>$uid]);
        //直接返回 不予
        if(empty($uid)){
            return false;
        }

        //1. 关联 $client_id 和 uid
        Gateway::bindUid($client_id, $uid);
        $_SESSION[$client_id] = $uid;// 使用session 进行关联 方便在 断开连接后 还能获取到uid


        //2. 获取用户当前已经加入的所有群组，依次加入所有群组中
        $groupList = UserListModel::findAll(['uid'=>$uid,'type'=>2],'mid');
        foreach ($groupList as $k=>$v){
            $group = "group_list:{$v['mid']}";
            Gateway::joinGroup($client_id, $group);
        }

        //3. 将所有用户 加入到大厅中。下线时 告知大厅中所有人
        $sala_list_key = "sala_list:{$userInfo['admin_id']}";
        Gateway::joinGroup($client_id, $sala_list_key);

        //4. 给大厅中 所有人 发送一个我上线了
        GatewayService::onlineState($userInfo,1);

        //获取我的未读消息数 并发送回去
        if($resData['getMsgNumber']==1){
            $where = [
                ['uid','=',$uid],
                ['msg_reda_number','>',0],
                ];
            //未读消息数
            $msg_reda_number = UserListModel::findSum($where,'msg_reda_number');
            GatewayService::toMsgRedaNumber($uid,$msg_reda_number);
        }

    }

}